import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import Routers from './router';
import Util from './libs/util';
import App from './app.vue';
import axios from 'axios'
import 'iview/dist/styles/iview.css';

Vue.use(VueRouter);
Vue.use(iView);
axios.defaults.baseURL = 'http://localhost:8088/';
Vue.prototype.$http = axios;
Vue.prototype.hasPermission = function (requirePermission) {
    var userPermission = sessionStorage.getItem("permission");
    if (userPermission == null) {
        return false;
    }
    else if (userPermission.indexOf(requirePermission) == -1) {
        return false;
    } else {
        return true;
    }
}
var myMenuItem = Vue.extend({
    name: 'myMenuItem',
    props: { item: {} },
    template: [
        ' <Submenu name="item.menuName" v-if="!item.menuUrl"><template slot="title"><Icon type="ios-paper">',
        '</Icon>{{item.menuName}}</template> <myMenuItem v-if="hasPermission(item.permission)" :item="item" v-for="item in item.children"></myMenuItem></Submenu>',
        '<Menu-item :name="item.menuUrl" v-else-if="item.menuUrl"><span class="layout-text">{{item.menuName}}</span></Menu-item>',
    ].join('')
});
Vue.component('myMenuItem', myMenuItem);
const RouterConfig = {
    mode: 'history',
    routes: Routers
};
const router = new VueRouter(RouterConfig);
router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    if (to.fullPath != '/views/common/login') {
        if (sessionStorage.getItem('token')) {  // 通过localStorage获取当前的token是否存在
            axios.defaults.headers = { 'Authorization': 'Bearer ' + sessionStorage.getItem('token') };
            next();
        } else {
            next('/views/common/login');
        }
    } else {
        next();
    }
});

router.afterEach((to, from, next) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});

new Vue({
    el: '#app',
    router: router,
    render: h => h(App)
});
